<?php
namespace App\Admin\Extensions;

use App\Models\Common\Media;
use Dcat\Admin\Form\Field\MultipleFile;
use Dcat\Admin\Support\Helper;

class MultpleFilePro extends MultipleFile
{
    public function __construct($column, $arguments = [])
    {
        parent::__construct($column, $arguments);

        $this->url('upload-file')->maxSize(1000 * 1024)->autoUpload()->saving(function ($value) {
            $mids = explode(',', $value);
            return $mids;
        });
    }

    protected function initialPreviewConfig()
    {
        $previews = [];

        foreach (Helper::array($this->value()) as $value) {
            if(is_integer($value)) {
                $media = Media::find($value);
                $previews[] = [
                    'id'   => $value,
                    'path' => $media->filename,
                    'url'  => $media->url,
                ];
            } else {
                $previews[] = [
                    'id'   => $value['id'],
                    'path' => $value['filename'],
                    'url'  => $value['url'],
                ];
            }
        }

        return $previews;
    }

    protected function prepareInputValue($file)
    {
        return $file;
    }

    protected function formatValue()
    {
        if ($this->value !== null) {
            $ids = array_column($this->value, 'id');
            $this->value = implode(',', $ids);
        } elseif (is_array($this->default)) {
            $this->default = implode(',', $this->default);
        }
    }
}
